package com.coder.oj.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.oj.admin.mapstruct.CaseMapstruct;
import com.coder.oj.admin.query.CaseQuery;
import com.coder.oj.admin.vo.CaseVo;
import com.coder.oj.admin.vo.KeyValueVo;
import com.coder.oj.common.core.JsonPage;
import com.coder.oj.common.core.R;
import com.coder.oj.common.entity.Case;
import com.coder.oj.common.enums.CommonStatusEnum;
import com.coder.oj.common.exception.DataException;
import com.coder.oj.common.mapper.AdminMapper;
import com.coder.oj.common.mapper.CaseMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Bosen 2022/11/25 11:26
 **/
@Service
public class CaseService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private CaseMapper caseMapper;

    @Autowired
    private CaseMapstruct caseMapstruct;

    /**
     * 分页查询
     * @author Bosen 2022/12/16 9:58
     **/
    public JsonPage<CaseVo> getCasePage(CaseQuery params) {
        LambdaQueryWrapper<Case> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(params.getProblemId()), Case::getProblemId, params.getProblemId());
        queryWrapper.eq(com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(params.getStatus()), Case::getStatus, params.getStatus());
        IPage<Case> page = caseMapper.selectPage(new Page<>(params.getPage(), params.getPageSize()), queryWrapper);
        List<CaseVo> collect = page.getRecords().stream().map(zase -> {
            CaseVo vo = caseMapstruct.toVO(zase);
            vo.setCreateBy(adminMapper.getAdminName(zase.getCreateBy()));
            vo.setUpdateBy(adminMapper.getAdminName(zase.getUpdateBy()));
            return vo;
        }).collect(Collectors.toList());
        return new JsonPage<>(page.getCurrent(), page.getSize(), page.getTotal(), collect);
    }

    /**
     * 样例列表
     * @author Bosen 2023/1/23 0:09
     */
    public List<KeyValueVo> getCaseListByProjectId(Long projectId) {
        List<Case> cases = caseMapper.selectList(Wrappers.lambdaQuery(Case.class)
                .eq(Case::getProblemId, projectId));
        return cases.stream().map(entity -> {
            KeyValueVo vo = new KeyValueVo();
            vo.setKey(entity.getInput());
            vo.setValue(entity.getOutput());
            return vo;
        }).collect(Collectors.toList());
    }
}
